//引入Food的类
import Food from './food'
// 引入ScorePanel的类
import ScorePanel from './scorepanel'
// 引入snake的类
import Snake from './snake'

class GameControl {
  snake:Snake
  food:Food
  scorepanel:ScorePanel
  //创建一个存放蛇运动的变量
  snakemove:string
  //创建一个变量存放是否还活着
  islive:boolean

  constructor() {
    this.snake = new Snake
    this.food = new Food
    this.scorepanel = new ScorePanel(10,3)
    this.snakemove = 'ArrowRight'
    this.islive = true

    //游戏初始化并开始
    this.init()
    this.run()
  }

  //游戏初始化，调用即是游戏开始
  init() {
    addEventListener('keyup', this.keyuphandle.bind(this))
  }

  keyuphandle(event:KeyboardEvent) {
    event = event || window.event
    this.snakemove = event.key
    console.log(this.snakemove);
    
  }

  run() {
    console.log("我进来了");
    
    //获取蛇当前的X坐标
    let X = this.snake.X
    //获取蛇当前的Y坐标
    let Y = this.snake.Y


    switch(this.snakemove) {
      //向上运动
      case'Up':
      case'ArrowUp':
        Y -=10
        break
      //向下运动
      case'Down':
      case'ArrowDown':
        Y += 10
        break
      //向左运动  
      case'Left':
      case'ArrowLeft':
        X -= 10
        break
      //向右运动
      case'Right':
      case'ArrowRight':
          X += 10
        break
    }

    //检测是否吃到食物
    this.checkeat(X,Y)

    //捕获异常
    try{
      //设置蛇的坐标值
      this.snake.X = X
      this.snake.Y = Y
    }catch(e) {
      window.alert("游戏结束！！！"+ e.message)
      this.islive = false
    }

    
    
    //自调用实现循环
    this.islive && setTimeout(this.run.bind(this), 300 - (this.scorepanel.level - 1) * 30)
  }

  //检测吃到食物的方法
  checkeat(X:number, Y:number) {
      if(X == this.food.X && Y == this.food.Y) {
        //食物刷新
        this.food.change()
        //分数增加
        this.scorepanel.addscore()
        //蛇身增加
        this.snake.addbody()
        
      }
  }

  
}

export default GameControl